<template>
  <div class="block">
    <el-pagination
      layout="prev, pager, next"
      :total="result.length"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handleCurrentChange"
      @next-click="nextClick"
      @prev-click="prevClick"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  props: {
    result: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      items: this.result, // 单向数据流拷贝的props中的数据
      pageSize: 8,
      currentPage: 1
    }
  },
  created () {
    this.setItems()
  },
  watch: {
    result: function (newVal, oldVal) {
      // console.log(newVal, oldVal)
      this.items = newVal
      this.setItems()
    }
  },
  methods: {
    prevClick () {
      this.currentPage--
      this.setItems()
    },
    nextClick () {
      this.currentPage++
      this.setItems()
    },
    setItems () {
      const list = this.items.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
      this.$emit('getItems', list)
    },
    handleCurrentChange (val) {
      this.currentPage = val
      this.setItems()
    }
  }
}
</script>

<style scoped>
/* 分页 */
.block {
  display: flex;
  justify-content: center;
  margin-top: 2rem;
}
</style>
